<?php


namespace app\common\model;


use think\Db;
use think\Model;

class Shop extends Model
{
    public function admin(){
        return $this->belongsTo('admin')->bind([
            'username','password'
        ]);
    }
    public function user(){
        return $this->belongsTo('user')->bind([
            'user_headimgurl'=>'headimgurl',
            'user_nickname'=>'nickname',
        ]);
    }

    public function shopCate(){
        return $this->belongsTo('shopCate');
    }

    public function getStateTextAttr($value,$data){
        $state = [
            10=>'营业中',
            20=>'暂停营业',
            30=>'已下架',
        ];
        return $state[$data['state']];
    }

    //    获取详情
    public static function getDetail($where){
        $data = self::with(['admin','user'])->where($where)->find();

        if (empty($data)){
            return $data;
        }

        $data['password'] = encry_code($data['password'],'DECODE');

        $data['img_thumb_online'] = $data->img_thumb;
        //            轮播图

        if (!empty($data['carousel'])){
            $carouselList = json_decode($data['carousel'],true);
            if (!empty($carouselList)){
                foreach ($carouselList as $k1=>&$v1){
                    if (!empty($v1)){
                        $carouselList[$k1]['url'] = getFullPath($v1['url']);
                    }else{
                        unset($carouselList[$k1]);
                    }
                }
            }

            $data['carouselList'] = $carouselList;
        }else{
            $data['carousel'] = [];
            $data['carouselList'] = [];
        }

        if (isset($data['business_hours'])){
            $data['business_hours'] = explode(',',$data['business_hours']);
        }


        if (isset($data['content'])){
            //改变路径
            $url = 'http://zl.bendijishi.xin.changtuchacha.com/';
            $pregRule = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.jpg|\.jpeg|\.png|\.gif|\.bmp]))[\'|\"].*?[\/]?>/";
            $data['content'] = preg_replace($pregRule, '<img src="'.$url.'${1}" style="max-width:100%">', $data['content']);
            //改变宽度
            $data['content'] = str_replace("<img ", "<img style='max-width:100%;height:auto;'", $data['content']);
        }

//        地址
        $data['area_code'] = Db::name('region')->where('cityName',$data['area'])->value('id');
        $data['area_full'] = $data['province'].$data['city'].$data['area'];

//        获取当前店铺的订单数量
        $data['order_num'] = Db::name('order')->where('shop_id','=',$data['id'])->count();

//        获取申请中的所有金额
        $data['cash_apply'] = ShopCash::where([['shop_id','=',$data['id']],['state','=',10]])->sum('money');

        return $data;
    }
}
